<template>
    <div id="tMapId"></div>
</template>

<script>
import axios from "axios";
import getdistance from "@/util/getdistance";
import { bd09togcj02, gcj02towgs84 } from "coordtransform";
export default {
    data() {
        return {
            map: null,
            mapData: [],
            searchAddress: [],
            highSpeed: [],//所有高速集合
            enlargeMarker: false,//控制marker是否变大
            polyline: null,
            markerArr: [],
            typeName: ''
        }
    },
    created() {
        this.getHtdata()
    },
    mounted() {
        console.log(getdistance);
        if (this.$route.query.type) {
            this.typeName = this.$route.query.type
        }
        this.getSeep()
        this.initMap()
    },
    activated() {
        if (this.$route.query.type) {
            this.typeName = this.$route.query.type
        }
    },
    methods: {
        getHtdata() {
            this.$http
                .post("/interflowInfo/selectInterflowInfoList", {
                    "pageIndex": "1", //当前页数
                    "pageSize": "100000" //每页显示记录数
                })
                .then((res) => {
                    console.log(res);
                    res.data.data.forEach(item => {
                        let J02Address = bd09togcj02(item.lon, item.lat);
                        let tAddress = gcj02towgs84(J02Address[0], J02Address[1])
                        item.lon = tAddress[0]
                        item.lat = tAddress[1];
                        var icon = new T.Icon({
                            iconUrl: "http://api.tianditu.gov.cn/v4.0/image/marker-icon.png",
                            iconSize: new T.Point(25, 32),
                            iconAnchor: new T.Point(10, 25)

                        });
                        var newMarker = new T.Marker(new T.LngLat(item.lon, item.lat), { icon: icon });
                        this.markerArr.push(newMarker)
                        this.getLabel(item)
                        //向地图上添加标注
                        this.map.addOverLay(newMarker);

                    })
                    this.mapData = res.data.data;
                    this.highSpeed = [...new Set(this.mapData.map(item => item.owningHighway))].sort()

                });
        },
        getLabel(point) {
            var latlng = new T.LngLat(point.lon, point.lat);
            var label = new T.Label({
                text: point.interflowName,
                position: latlng,
                offset: new T.Point(-9, 0)
            });
            //创建地图文本对象
            this.map.addOverLay(label);
        },
        getSeep() {
            this.$http.post('/interflowInfo/selectHighSpeedWayInfoList').then(res => {
                this.speedList = res.data
            })
        },
        initMap() {
            let that = this  //将方法放在mounted，会有指向问题，定义this使用就会正常
            let zoom = 12; //地图的初始化级别，及放大比例
            that.map = new T.Map("tMapId");
            that.map.centerAndZoom(new T.LngLat(112.56, 37.86), zoom); //地图的初始化中心点，此为北京的经纬度
            // that.map.setMapCursor("crosshair");
            that.map.addEventListener('click', (e) => {
                this.locationAddress(e.lnglat, 'click');

            })
            that.map.addEventListener('mousemove', (e) => {
                console.log("数据111：", e.originalEvent.toElement.style);
              
                this.enlargeMarker = true
                this.locationAddress(e.lnglat, 'mousemove',e);
                // setTimeout(()=>{
                //    
                // },20000)
                // 设置为自定义图像
                // this.map.setDefaultCursor("crosshair");
                // that.map.setDefaultCursor("url('http://www.example.com/customcursor.cur'), auto");
            })

        },
        locationAddress(val, type,e) {
            axios({
                method: "get",
                url: "http://api.tianditu.gov.cn/geocoder",
                params: {
                    tk: "9f14fcb360e1f89077fdec6c7d17fa6e",
                    type: "geocode",
                    postStr:
                        "{'lon':" +
                        val.lng +
                        ",'lat':" +
                        val.lat +
                        ",'ver':1}",
                },
            }).then((res) => {
                console.log("数据：", res.data.result);
                if (type == 'click') {
                    this.setMapData(res.data.result.addressComponent.road, res.data.result.location)

                } else {
                    if (res.data.result.addressComponent.road.includes('高速')) {
                        console.log('点击位置属于高速公路');
                        e.originalEvent.toElement.style.cursor='pointer'
                        if (this.speedLabel) {
                            this.map.removeOverLay(this.speedLabel);
                        }
                        //判断高速中包含地址的高速
                        let AllSpeed = this.highSpeed.filter(item => res.data.result.addressComponent.road.includes(item))
                        console.log(AllSpeed, '属于高速公路');
                        let speedRepeat = AllSpeed.length > 0 ? AllSpeed[AllSpeed.length - 1] : AllSpeed[0];
                        let currentSpeed = this.highSpeed.find(item => item == speedRepeat)
                        console.log(this.highSpeed, '属于高速公路');
                        console.log(currentSpeed, '当前高速公路');
                        var latlng = new T.LngLat(val.lng, val.lat);
                        this.speedLabel = new T.Label({
                            text: currentSpeed,
                            position: latlng,
                            offset: new T.Point(-9, 0)
                        });
                        //创建地图文本对象
                        this.map.addOverLay(this.speedLabel);
                        this.searchSpeed(res.data.result.location, currentSpeed)
                    } else {
                        this.enlargeMarker = true
                        e.originalEvent.toElement.style.cursor='grab'
                        console.log('不是高速', this.searchAddress);
                        // if (this.searchAddress.length > 1) {
                        this.searchAddress.forEach(item => {
                            this.updataMarker(item)
                        })
                        //     // this.addLine()
                        // }
                    }
                }

            });

        },
        setMapData(address, point) {
            if (address.includes('高速')) {
                console.log('点击位置属于高速公路');

                //判断高速中包含地址的高速
                let AllSpeed = this.highSpeed.filter(item => address.includes(item))
                console.log(AllSpeed, '属于高速公路');
                let speedRepeat = AllSpeed.length > 0 ? AllSpeed[AllSpeed.length - 1] : AllSpeed[0];
                let currentSpeed = this.highSpeed.find(item => item == speedRepeat)
                console.log(this.highSpeed, '属于高速公路');
                console.log(currentSpeed, '当前高速公路');
                this.searchSpeed(point, currentSpeed)
                this.addLine()

            } else {
                this.$message.error('未点击到高速公路')
                console.log('点击位置不属于高速公路');
            }
        },
        searchSpeed(point, val) {
            this.$http.post('/interflowInfo/selectInterflowInfoListByHighWayName', { owningHighway: val }).then(res => {
                console.log(res);
                //     //测算最近互通的两点
                res.data.data.forEach(item => {
                    let J02Address = bd09togcj02(item.lon, item.lat);
                    let tAddress = gcj02towgs84(J02Address[0], J02Address[1])
                    item.lon = tAddress[0]
                    item.lat = tAddress[1];
                    item.distance = getdistance.getGreatCircleDistance(point.lon, point.lat, item.lon, item.lat)

                })
                let distanceArr = res.data.data.sort((a, b) => a.distance - b.distance)
                this.searchAddress = distanceArr.splice(0, 2)
                console.log(this.searchAddress, '当前高速的互通');
                this.enlargeMarker = false
                if (this.searchAddress.length > 1) {
                    this.searchAddress.forEach(item => {
                        this.updataMarker(item)
                    })

                }

            })
        },
        updataMarker(val) {
            let index = this.mapData.findIndex(current => current.id == val.id);
            let currentItem = this.mapData.find(current => current.id == val.id);
            if (this.enlargeMarker) {
                this.map.removeOverLay(this.markerArr[index]);
                var icon = new T.Icon({
                    iconUrl: "http://api.tianditu.gov.cn/v4.0/image/marker-icon.png",
                    iconSize: new T.Point(25, 32),
                    iconAnchor: new T.Point(10, 25)

                });
                var newMarker = new T.Marker(new T.LngLat(currentItem.lon, currentItem.lat), { icon: icon });
                this.markerArr.splice(index, 1, newMarker)
                //向地图上添加标注
                this.map.addOverLay(newMarker);
            } else {
                if (index != -1) {
                    this.map.removeOverLay(this.markerArr[index]);

                    var icon = new T.Icon({
                        iconUrl: "http://api.tianditu.gov.cn/v4.0/image/marker-icon.png",
                        iconSize: new T.Point(35, 42),
                        iconAnchor: new T.Point(10, 25)

                    });
                    var newMarker = new T.Marker(new T.LngLat(currentItem.lon, currentItem.lat), { icon: icon });
                    this.markerArr.splice(index, 1, newMarker)
                    //向地图上添加标注
                    this.map.addOverLay(newMarker);
                }
            }


        },
        addLine() {
            let that = this
            if (this.polyline) {
                that.map.removeOverLay(this.polyline);
            }


            const path = [
                new T.LngLat(this.searchAddress[0].lon, this.searchAddress[0].lat),
                new T.LngLat(this.searchAddress[1].lon, this.searchAddress[1].lat),
            ]

            // 创建线对象
            this.polyline = new T.Polyline(path, {
                color: 'blue', // 线颜色
                weight: 3,     // 线宽
                opacity: 1,    // 线透明度
                fillColor: "#FFFFFF", //填充颜色。
                fillOpacity: 0.3 //填充透明度
            });
            // 将线对象添加到地图上
            that.map.addOverLay(this.polyline);
            let speedName = ''
            if (this.searchAddress[0].interflowAlias) {
                speedName = this.searchAddress[0].interflowAlias + '-' + this.searchAddress[0].interflowName + '至' + this.searchAddress[1].interflowName;
            } else {
                speedName = this.searchAddress[0].owningHighway + '-' + this.searchAddress[0].interflowName + '至' + this.searchAddress[1].interflowName;
            }
            console.log(speedName, '当前高速的互通');
            this.$router.push({
                path: '/home',
                query: {
                    params: speedName,
                    typeName: this.typeName
                }
            })


        }
    }
}
</script>

<style>
#tMapId {
    height: 100%;
}
</style>